{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-11-10T05:32:34.171615Z",
     "start_time": "2020-11-10T05:32:34.148159Z"
    }
   },
   "outputs": [],
   "source": [
    "from moviepy.editor import *\n",
    "import pandas as pd\n",
    "def cut(file):\n",
    "    print('读取视频')\n",
    "    clip2 = VideoFileClip(file)\n",
    "    print('读取音频')\n",
    "    audioclip = clip2.audio\n",
    "    soundarray = audioclip.to_soundarray()\n",
    "    soundarray = pd.DataFrame(soundarray)\n",
    "    soundarray = abs(soundarray)\n",
    "    print('读取音量低的部分')\n",
    "    yuzhi = 0.02\n",
    "    gap = 0.01\n",
    "    a = pd.DataFrame(list(soundarray[soundarray[0]<yuzhi].index/44100)).round(2)\n",
    "    a['count'] = 1\n",
    "    a = (a.groupby(0)['count'].sum()/(44100*gap))\n",
    "    rate = 0.8\n",
    "    a = a[a<rate]\n",
    "    a = list(a.index)\n",
    "    a = pd.DataFrame(a,columns = ['x'])\n",
    "    a['x_1'] = a.shift(-1)\n",
    "    a['flag'] = a['x_1']-a['x']\n",
    "    a = a[a['flag']>gap*1.1]\n",
    "    ls = []\n",
    "    for i in range(len(a)-1):\n",
    "        ls.append([a.iloc[i]['x_1'],a.iloc[i+1]['x']])\n",
    "    print('裁剪')\n",
    "    clips = []\n",
    "    for i in ls:\n",
    "        if i[0]<i[1]:\n",
    "            clips.append(clip2.subclip(i[0],i[1]))\n",
    "    print('渲染合成')\n",
    "    finalclip = concatenate_videoclips(clips)\n",
    "    finalclip.write_videofile('cliped'+file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-11-10T05:13:11.064731Z",
     "start_time": "2020-11-10T04:30:38.360252Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "filelist = os.listdir()\n",
    "for file in filelist:\n",
    "    if file.split('.')[1]=='mp4':\n",
    "        print(file)\n",
    "        cut(file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cut('测试视频.mp4')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
